using System;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using Microsoft.TeamFoundation.Client;

namespace CodeGears.WorkItemTracking.ChartingDashboard
{
    public class MainViewModel : ViewModeBase
    {
        private MainView MainView { get; set; }
        private Timer _timer;

        private ICommand _addChartCommand;
        public ICommand AddChartCommand
        {
            get
            {
                if (_addChartCommand == null)
                {
                    _addChartCommand = new DelegateCommand(AddChart);
                }
                return _addChartCommand;
            }
        }

        private ICommand _connectCommand;
        public ICommand ConnectCommand
        {
            get
            {
                if (_connectCommand == null)
                {
                    _connectCommand = new DelegateCommand(() => LogIn(true));
                }
                return _connectCommand;
            }
        }

        public string ServerAddress { get; set; }

        public MainViewModel(MainView mainView)
        {
            MainView = mainView;
            ServerAddress = "https://tfs06.codeplex.com:443/";
            //ServerAddress = "http://diamond:8080/";
        }

        public void StartLoginTimer()
        {
            _timer = new Timer(500);
            _timer.Elapsed += (s, e) => Connect();
            _timer.Start();
        }

        private void Connect()
        {
            _timer.Stop();

            MainView.ShowLoginBox();
        }

        private TeamFoundationServer LogIn(bool firstTimeLogin)
        {
            if(firstTimeLogin)
            {
                MainView.HideLoginBox();
            }

            try
            {
                var server = TeamFoundationServerFactory.GetServer(ServerAddress, new UICredentialsProvider());
                server.Authenticate();

                if (firstTimeLogin)
                {
                    MainView.StartAnimation();
                }

                return server;
            }
            catch
            {
                MessageBox.Show(String.Format("Could not connect to {0}", ServerAddress), "Connection error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return null;
        }

        private void AddChart()
        {
            var server = LogIn(false);

            var model = new ChartViewModel(server);
            model.LoadProjects();

            var view = new ChartView { DataContext = model };
            view.SetData(model.Series);

            MainView.AddChart(view);
        }
    }
}